package com.weilus.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Configuration
@ConfigurationProperties(prefix = "spring.cache.redis")
public class RedisConfig {

    private Map<String, Duration>  timeToLives;

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory){
        Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
        timeToLives.forEach((k,v)->cacheConfigurations.put(k,RedisCacheConfiguration.defaultCacheConfig().entryTtl(v)));
        return RedisCacheManager.RedisCacheManagerBuilder
                .fromConnectionFactory(connectionFactory)
                .withInitialCacheConfigurations(cacheConfigurations)
                .build();
    }

    public void setTimeToLives(Map<String, Duration> timeToLives) {
        this.timeToLives = timeToLives;
    }
}
